import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import { METHODS } from 'http';
let isDev = process.env.NODE_ENV === 'development';  //判断是不是开发环境
Vue.use(Vuex)

export default new Vuex.Store({
    strict: isDev, //防止外部修改state里的值，尽量不要在正式环境中使用。（传入true活着false）
    state: {
        userName: 'user',
        text: '',
        list: [
            {
                name: '小赵',
                index: '1'
            },
            {
                name: '小钱',
                index: '2'
            },
            {
                name: '小孙',
                index: '3'
            },
            {
                name: '小李',
                index: '4'
            }
        ]
    },
    mutations: {   //改变数据必须是同步的，不能有异步操作
        CHANGE_NAME(state, name) {
            state.userName = name
        },
        CHANGE_TEXT(state, name) {
            state.text = name
        }
    },
    getters: {   //作用（把state状态的数据进行一次映射或者筛选）
        newList(state) {
            return state.list.filter(item => item.index > 2)
        }
    },
    actions: {  //处理异步操作
        setName(store, data) {
            store.commit('CHANGE_NAME', data);
        },
        getText(store, data) {
            fetch("https://api.uixsj.cn/hitokoto/get?type=social")
                .then((res) => res.text())
                .then((res) => {
                    store.commit('CHANGE_TEXT', res);
                });
        }
    },
    // plugins: [createPersistedState({
    //     storage: {
    //         getItem: key => sessionStorage.getItem(key),
    //         // Please see https://github.com/js-cookie/js-cookie#json, on how to handle JSON.
    //         setItem: (key, value) =>
    //             sessionStorage.setItem(key, value),
    //         removeItem: key => sessionStorage.removeItem(key),
    //     },
    // })],

})